package com.xiaoma.lock;

import java.util.HashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author xiaomacdut
 * @date 2020年2月7日 上午11:48:40
 */
public class SysDemoTest implements Runnable{
    
    private HashMap<String, Integer> map;
    
    private CountDownLatch latch;
    
    private CountDownLatch end;
    
    private ReentrantLock lock;
    
    SysDemoTest(HashMap<String, Integer> map, CountDownLatch latch, ReentrantLock lock, CountDownLatch end){
        this.map = map;
        this.latch = latch;
        this.lock = lock;
        this.end = end;
    }
    
    public void run(){
        try{
            latch.await();// 阻塞
        }catch(InterruptedException e){
            e.printStackTrace();
        }
        
        for(int i = 0; i < 100000; i++){
            lock.lock();
            try{
                Integer z = map.get("1");
                map.put("1", ++z);
            }finally{
                lock.unlock();
            }
        }
        end.countDown();
    }
    
    synchronized void add(){
        Integer i = map.get("1");
        map.put("1", ++i);
        
    }
    
    
    public static void main(String [] args){
        ReentrantLock lock = new ReentrantLock();
        CountDownLatch latch = new CountDownLatch(1000);
        CountDownLatch end = new CountDownLatch(1000);
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        
        map.put("1", 0);
        long start = System.currentTimeMillis();
        SysDemoTest test = new SysDemoTest(map, latch, lock, end);
        
        for(int i = 0; i < 1000; i++){
            Thread t = new Thread(test);
            t.start();
            latch.countDown();
        }
        
        try{
            end.await();
        }catch(InterruptedException e){
            e.printStackTrace();
        }
        
        System.out.println(System.currentTimeMillis() - start);
        System.out.println(map.get("1"));
    }
    
}
